package handlers

import (
	"encoding/json"
	"net/http"
	"skedule-backend/utils"
)

// APIResponse 统一的API响应结构
type APIResponse struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data,omitempty"`
}

// Success 成功响应
func Success(w http.ResponseWriter, data interface{}) {
	SuccessWithMsg(w, utils.T("api.success"), data)
}

// SuccessWithMsg 成功响应带消息
func SuccessWithMsg(w http.ResponseWriter, msg string, data interface{}) {
	response := APIResponse{
		Code: 0,
		Msg:  msg,
		Data: data,
	}
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(response)
}

// Error 错误响应
func Error(w http.ResponseWriter, code int, msg string) {
	response := APIResponse{
		Code: code,
		Msg:  msg,
	}
	w.Header().Set("Content-Type", "application/json")
	
	// 根据错误码设置HTTP状态码
	httpStatus := http.StatusOK // 默认200，业务错误通过code字段区分
	if code >= 1000 { // 服务器错误
		httpStatus = http.StatusInternalServerError
	} else if code >= 400 { // 客户端错误
		httpStatus = http.StatusBadRequest
	}
	
	w.WriteHeader(httpStatus)
	json.NewEncoder(w).Encode(response)
}

// ErrorWithData 错误响应带数据
func ErrorWithData(w http.ResponseWriter, code int, msg string, data interface{}) {
	response := APIResponse{
		Code: code,
		Msg:  msg,
		Data: data,
	}
	w.Header().Set("Content-Type", "application/json")
	
	// 根据错误码设置HTTP状态码
	httpStatus := http.StatusOK
	if code >= 1000 {
		httpStatus = http.StatusInternalServerError
	} else if code >= 400 {
		httpStatus = http.StatusBadRequest
	}
	
	w.WriteHeader(httpStatus)
	json.NewEncoder(w).Encode(response)
}

// 预定义错误响应函数
func BadRequest(w http.ResponseWriter, msg string) {
	if msg == "" {
		msg = utils.T("api.bad.request")
	}
	Error(w, CodeBadRequest, msg)
}

func Unauthorized(w http.ResponseWriter) {
	Error(w, CodeUnauthorized, utils.T("api.unauthorized"))
}

func NotFound(w http.ResponseWriter) {
	Error(w, CodeNotFound, utils.T("api.not.found"))
}

func InternalError(w http.ResponseWriter, msg string) {
	if msg == "" {
		msg = utils.T("api.internal.error")
	}
	Error(w, CodeInternalError, msg)
}

// 常用错误码
const (
	// 成功
	CodeSuccess = 0
	
	// 客户端错误 (400-499)
	CodeBadRequest     = 400
	CodeUnauthorized   = 401
	CodeForbidden      = 403
	CodeNotFound       = 404
	CodeValidationFail = 422
	
	// 服务器错误 (1000+)
	CodeInternalError  = 1000
	CodeDatabaseError  = 1001
	CodeSchedulerError = 1002
) 